package com.jinwei.qunguanjia.web.user.controller;

import com.jinwei.qunguanjia.common.core.domain.Response;
import com.jinwei.qunguanjia.common.core.domain.model.LoginUser;
import com.jinwei.qunguanjia.common.core.page.PageDataInfo;
import com.jinwei.qunguanjia.common.core.redis.RedisCache;
import com.jinwei.qunguanjia.common.utils.*;
import com.jinwei.qunguanjia.common.utils.http.HttpUtils;
import com.jinwei.qunguanjia.user.dto.GroupDTO;
import com.jinwei.qunguanjia.user.dto.UserIntegralDTO;
import com.jinwei.qunguanjia.user.dto.UserDTO;
import com.jinwei.qunguanjia.user.dto.UserVerificationCodeDTO;
import com.jinwei.qunguanjia.user.service.*;
import com.jinwei.qunguanjia.web.group.vo.GroupVO;
import com.jinwei.qunguanjia.web.user.vo.UserVO;
import com.jinwei.qunguanjia.web.wechat.service.WxAsyncTemplateMessageService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录相关接口
 *
 * @author yuanzs
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private RedisCache redisCache;

    @Resource
    private UserTokenService tokenService;

    @Resource
    private UserService userService;

    @Resource
    private UserVerificationCodeService userVerificationCodeService;

    @Resource
    private GroupService groupService;

    @Resource
    private UserIntegralService userIntegralService;

    @Resource
    private WxAsyncTemplateMessageService wxAsyncTemplateMessageService;
    /**
     * 用户登录
     * @param userVO 对象
     */
    @PostMapping("/login")
    public Response login(@Validated @RequestBody UserVO userVO) throws IllegalAccessException {
        String token = redisCache.getCacheObject(tokenService.getUserNameKey(userVO.getPhoneNumber()));
        if(null != token){
            redisCache.deleteObject(tokenService.getUserNameKey(userVO.getPhoneNumber()));
            redisCache.deleteObject(tokenService.getTokenKey(token));
        }
        if ("18611111111".equals(userVO.getPhoneNumber())) {
            if (!"1111".equals(userVO.getVerificationCode())) {
                return Response.fail("验证码错误");
            }
        } else {
            UserVerificationCodeDTO userVerificationCodeDTO = new UserVerificationCodeDTO();
            userVerificationCodeDTO.setPhoneNumber(userVO.getPhoneNumber());
            userVerificationCodeDTO = userVerificationCodeService.get(userVerificationCodeDTO);
            if (null == userVerificationCodeDTO) {
                return Response.fail("验证码错误");
            } else if (!userVO.getVerificationCode().equals(userVerificationCodeDTO.getVerificationCode())) {
                return Response.fail("验证码错误");
            }
        }
        UserDTO userDTO = userService.get(UserDTO.builder().phoneNumber(userVO.getPhoneNumber()).build());
        if (null == userDTO) {
            userDTO = UserDTO.builder().build();
            BeanUtils.copyProperties(userVO, userDTO);
            String userId = userService.save(userDTO);
            userDTO.setUserId(userId);
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(userDTO.getUserId());
        loginUser.setUserName(userDTO.getPhoneNumber());
        token = tokenService.createToken(loginUser);
        if (userVO.getDeviceType() != null && userVO.getDeviceToken() != null) {
            UserDTO userTokenDTO = new UserDTO();
            userTokenDTO.setUserId(userDTO.getUserId());
            userTokenDTO.setDeviceType(userVO.getDeviceType());
            userTokenDTO.setDeviceToken(userVO.getDeviceToken());
            userService.update(userDTO);
        }

        List<WxMpTemplateData> data = Arrays.asList(
                new WxMpTemplateData("thing1", "userlogin:" + userVO.getPhoneNumber()),
                new WxMpTemplateData("time2", DateUtils.getDateTime())
        );
        wxAsyncTemplateMessageService.sendTemplateMessageByOpenId("o_hhj5396JBrpdzKoHdFwe7P3hAI", "tB3SORRpzzOMovuscTMZcRBWMDQKReKUl2fQoRgpe04", data, "");

        return Response.success(token);
    }

    /**
     * 发送验证码
     * @param userVO 手机号
     */
    @PostMapping("/send/verificationCode")
    public Response sendVerificationCode(@RequestBody UserVO userVO) {
        UserVerificationCodeDTO userVerificationCodeDTO = new UserVerificationCodeDTO();
        userVerificationCodeDTO.setPhoneNumber(userVO.getPhoneNumber());
        String randomCode = RandomUtils.getRandomCode(4);
        userVerificationCodeDTO.setVerificationCode(randomCode);
        userVerificationCodeService.save(userVerificationCodeDTO);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("mobile", userVO.getPhoneNumber());
        paramMap.put("tpl_id", 253348);
        paramMap.put("vars", "{\"code\":"+randomCode+"}");
        paramMap.put("key", "f7cd76e57466ae37c8d8238a7d5d07a8");
        HttpUtils.sendPostForm("http://v.juhe.cn/sms/send", null, paramMap);
        return Response.success();
    }

    /**
     * 修改用户
     * @param userVO 对象
     */
    @PutMapping("/update")
    public Response update(@Validated @RequestBody UserVO userVO) {
        synchronized (this) {
            UserDTO userDTO = new UserDTO();
            BeanUtils.copyProperties(userVO, userDTO);
            userDTO.setUserId(SystemContextUtils.getUserId());
            UserDTO userQueryDTO = userService.get(userDTO.getUserId());
            int myIntegral = Integer.parseInt(userQueryDTO.getMyIntegral());
            if (StringUtils.isEmpty(userQueryDTO.getRealName())) {
                UserIntegralDTO integralDTO = UserIntegralDTO.builder()
                        .integralType("0")
                        .integralSource("2")
                        .integralNumber("1")
                        .userId(SystemContextUtils.getUserId())
                        .build();
                userIntegralService.save(integralDTO);
                myIntegral = myIntegral + 1;
                userDTO.setMyIntegral(String.valueOf(myIntegral));
            }
            if (StringUtils.isEmpty(userQueryDTO.getWeChatNumber())) {
                UserIntegralDTO integralDTO = UserIntegralDTO.builder()
                        .integralType("0")
                        .integralSource("2")
                        .integralNumber("1")
                        .userId(SystemContextUtils.getUserId())
                        .build();
                userIntegralService.save(integralDTO);
                myIntegral = myIntegral + 1;
                userDTO.setMyIntegral(String.valueOf(myIntegral));
            }
            userService.update(userDTO);
            return Response.success();
        }
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public Response<UserVO> getInfo() {
        UserDTO userQueryDTO = userService.get(SystemContextUtils.getUserId());
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userQueryDTO, userVO);
        return Response.success(userVO);
    }

    /**
     * 我的发布分页列表
     */
    @GetMapping("/group/listPage")
    public PageDataInfo<GroupVO> list() throws IllegalAccessException {
        GroupDTO groupDTO = new GroupDTO();
        groupDTO.setUserId(SystemContextUtils.getUserId());
        PageUtils.startPage();
        PageDataUtil<GroupDTO, GroupVO> pageDataUtil = new PageDataUtil<>();
        return pageDataUtil.transform(groupService.listMyPublishPage(groupDTO), GroupVO.class);
    }
    /**
     * 注销接口
     */
    @DeleteMapping("/logout")
    public Response logout() {
        userService.logout(SystemContextUtils.getUserId());
        return Response.success();
    }
}
